package com.invest.infra.excel.wrapper.impl;


import com.google.common.collect.Maps;
import com.invest.infra.excel.wrapper.ExSheet;
import com.invest.infra.excel.wrapper.ExWorkbook;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

public class ExWorkbookImpl implements ExWorkbook {
	
	private Workbook wb;
	     
	private Map<String,ExSheet> map = Maps.newLinkedHashMap();
	
	private String name;
	
	private ExWorkbookImpl(Workbook wb, String fileName){
		
		this.wb = wb;
		this.name = fileName;
	}

	public static ExWorkbook instance(Workbook wb, String fileName){
		ExWorkbookImpl workbook = new ExWorkbookImpl(wb,fileName);
		workbook.initMap();
		return workbook;
	}

	@Override
	public Workbook getPoiWorkbook() {
		return wb;
	}

	@Override
	public Map<String,ExSheet> getSheets() {
		return map;
	}

	@Override
	public void write(OutputStream out) {
		try {
			wb.write(out);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void close() {
		try {
			wb.close();
		}catch (IOException ex){
			throw new RuntimeException(ex);
		}
	}


	@Override
	public String getName() {
		return name;
	}

	private void initMap(){
		
		int sheetCount = wb.getNumberOfSheets();
		for(int i=0; i< sheetCount ;i++){
			initRealMap(i, wb.getSheetName(i));
		}
	}

	private void initRealMap(int i, String sheetName) {
		Sheet poiSheet = wb.getSheetAt(i);
		if(poiSheet != null && StringUtils.isNotBlank(sheetName)){
			ExSheet sheet = ExSheetImpl.instance(this,poiSheet);
			map.put(sheetName, sheet);
		}
	}
}
